#!/usr/bin/env python

import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

from sudoku import parse_grid
from sudoku import search
from sudoku import rows, cols

def htmlboard(values, name):
    path = os.path.join(os.path.dirname(__file__), '%s.html' % name)
    return template.render(path, { 'values': values })

class MainPage(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, {
            'rows' : rows,
            'cols' : cols }
            ))

class Solution(webapp.RequestHandler):
    def post(self):
        input = ""
        for r in rows:
            for c in cols:
                input += self.request.get(r+c)

        alternatives = parse_grid(input)
        solution = search(alternatives) if alternatives else False
        path = os.path.join(os.path.dirname(__file__), 'solution.html')
        self.response.out.write(template.render(path, {
            'alternatives' : htmlboard(alternatives, 'board_vanilla') if alternatives else False,
            'solution': htmlboard(solution, 'board_final') if solution else False }
            ))


application = webapp.WSGIApplication(
        [('/', MainPage), ('/solution', Solution)], debug=True)

def main():
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
